﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace 建邦配料系统
{
    internal class SMQ_ScaleTcpClient
    {

        private TcpClient _client;
        private NetworkStream _stream;
        private CancellationTokenSource _cts;
        public bool IsConnected => _client?.Connected == true;

        public event Action<string> DataReceived;
        public event Action<string> LogMessage;

        public async Task SMQ_ConnectAsync(string ip, int port)
        {
            try
            {
                _client = new TcpClient();
                await _client.ConnectAsync(ip, port);
                _stream = _client.GetStream();
                _cts = new CancellationTokenSource();

                LogMessage?.Invoke($"已连接到 {ip}:{port} 扫码枪");
                SMQ_StartListening();
            }
            catch (Exception ex)
            {
                LogMessage?.Invoke($"扫码枪连接错误: {ex.Message}");
            }
        }

        public bool SMQ_Reconnect()
        {
            try
            {
                if (_client.Client.Connected)
                {
                    return false;
                }
                return true;
            }
            catch (Exception ex) { return true; }

        }

        private void SMQ_StartListening()
        {
            Task.Run(async () =>
            {
                byte[] buffer = new byte[1024];
                while (!_cts.IsCancellationRequested)
                {
                    try
                    {
                        int bytesRead = await _stream.ReadAsync(buffer, 0, buffer.Length, _cts.Token);
                        if (bytesRead > 0)
                        {
                            string data = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                            DataReceived?.Invoke(data);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (!_cts.IsCancellationRequested)
                            LogMessage?.Invoke($"接收错误: {ex.Message}");
                        break;
                    }
                }
            }, _cts.Token);
        }

        public async Task SMQ_SendCommandAsync(string command)
        {
            if (!IsConnected) return;

            try
            {
                byte[] data = Encoding.ASCII.GetBytes(command);
                await _stream.WriteAsync(data, 0, data.Length);
                LogMessage?.Invoke($"已发送: {command}");
            }
            catch (Exception ex)
            {
                LogMessage?.Invoke($"发送错误: {ex.Message}");
            }
        }

        public void SMQ_Disconnect()
        {
            _cts?.Cancel();
            _stream?.Close();
            _client?.Close();
            LogMessage?.Invoke("连接已断开");
        }
    }
}

